<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件下载与上传</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f4f7fa;
            margin: 0;
            padding: 20px;
            color: #333;
        }

        .container {
            max-width: 900px;
            margin: 0 auto;
            background: #ffffff;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        h1 {
            text-align: center;
            color: #2c3e50;
            margin-bottom: 30px;
        }

        h2 {
            color: #34495e;
            border-bottom: 2px solid #3498db;
            padding-bottom: 5px;
            margin-top: 30px;
            margin-bottom: 15px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }

        table tr {
            border-bottom: 1px solid #ddd;
        }

        table tr:last-child {
            border-bottom: none;
        }

        table td {
            padding: 12px;
        }

        table td:nth-child(2),
        table td:nth-child(3) {
            text-align: right;
        }

        table td:nth-child(4) {
            text-align: left;
            padding: 12px;
        }

        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-top: 20px;
            gap: 5px;
        }

        .pagination button {
            padding: 6px 10px;
            border: 1px solid #ccc;
            background: #fff;
            cursor: pointer;
            border-radius: 4px;
        }

        .pagination button:hover:not(:disabled) {
            background: #f0f0f0;
        }

        .pagination button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .pagination .page-info {
            margin: 0 10px;
            font-size: 14px;
            color: #666;
        }

        form {
            background: #f8f9fa;
            padding: 25px;
            border-radius: 8px;
            border: 1px solid #e1e8ed;
            margin-top: 30px;
        }

        .upload-area {
            margin-bottom: 15px;
        }

        .file-input-wrapper {
            position: relative;
            display: inline-block;
            cursor: pointer;
            width: 100%;
        }

        .file-input-wrapper input[type="file"] {
            position: absolute;
            left: -9999px;
        }

        .file-input-label {
            display: block;
            padding: 12px 20px;
            background: #3498db;
            color: white;
            border-radius: 6px;
            text-align: center;
            cursor: pointer;
            transition: background 0.3s;
        }

        .file-input-label:hover {
            background: #2980b9;
        }

        .upload-button {
            display: block;
            width: 200px;
            margin: 20px auto;
            padding: 12px;
            background: #27ae60;
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 16px;
            cursor: pointer;
            transition: background 0.3s;
        }

        .upload-button:hover {
            background: #229954;
        }

        .file-info {
            margin-top: 10px;
            font-size: 14px;
            color: #666;
        }

        /* 进度条样式 */
        .progress-container {
            width: 100%;
            margin: 15px 0;
            background: #e0e0e0;
            border-radius: 10px;
            overflow: hidden;
            display: none;
        }

        .progress-bar {
            height: 20px;
            background: #3498db;
            width: 0%;
            transition: width 0.3s;
        }

        .progress-text {
            display: block;
            text-align: center;
            font-size: 12px;
            color: #555;
            margin-top: 5px;
        }

        /* 多文件进度条样式 */
        .file-progress-item {
            margin-bottom: 10px;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 5px;
        }

        .file-progress-item .file-name {
            font-weight: bold;
            margin-bottom: 5px;
        }

        .file-progress-item .progress-container {
            background: #e0e0e0;
            border-radius: 5px;
            overflow: hidden;
        }

        .file-progress-item .progress-bar {
            height: 15px;
            background: #3498db;
        }

        .file-progress-item .progress-text {
            font-size: 12px;
            color: #666;
        }

        /* 上传结果样式 */
        .upload-result {
            margin-top: 15px;
            padding: 15px;
            border-radius: 5px;
            background: #f8f9fa;
            border: 1px solid #e1e8ed;
        }

        .upload-result-title {
            font-weight: bold;
            margin-bottom: 10px;
        }

        .upload-result-list {
            max-height: 200px;
            overflow-y: auto;
        }

        .upload-success {
            color: #27ae60;
        }

        .upload-failed {
            color: #e74c3c;
        }

        .upload-result-item {
            margin: 5px 0;
            padding: 5px;
            border-bottom: 1px solid #eee;
        }

        .upload-result-item:last-child {
            border-bottom: none;
        }

        .page-size-selector {
            display: flex;
            align-items: center;
            justify-content: flex-end;
            margin-bottom: 15px;
        }

        .page-size-selector label {
            margin-right: 10px;
            font-size: 14px;
            color: #666;
        }

        .page-size-selector select {
            padding: 5px 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background: white;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <div class="container">
        <h1>文件下载与上传</h1>

        <!-- 可下载文件列表 -->
        <h2>可下载文件列表</h2>

        <div class="page-size-selector">
            <label for="pageSizeSelect">每页显示的文件数：</label>
            <select id="pageSizeSelect">
                <option value="5">5</option>
                <option value="10">10</option>
                <option value="20">20</option>
                <option value="50">50</option>
                <option value="100">100</option>
            </select>
        </div>

        <table id="fileTable">
            <thead>
                <tr>
                    <th style="text-align: left; padding: 12px;">文件名</th>
                    <th style="text-align: right; padding: 12px;">上传时间</th>
                    <th style="text-align: right; padding: 12px;">大小</th>
                    <th style="text-align: left; padding: 12px;">操作</th>
                </tr>
            </thead>
            <tbody id="fileTableBody">
                <!-- JS 动态填充 -->
            </tbody>
        </table>

        <div class="pagination" id="pagination">
            <!-- JS 动态生成 -->
        </div>

        <!-- 上传新文件 -->
        <h2>上传新文件</h2>
        <form id="uploadForm">
            <div class="upload-area">
                <div class="file-input-wrapper">
                    <input type="file" id="fileInput" name="file" multiple />
                    <label for="fileInput" class="file-input-label">
                        ➕ 点击选择文件（可多选）
                    </label>
                </div>
                <div class="file-info" id="fileInfo">暂未选择文件</div>
            </div>

            <!-- 总进度条 -->
            <div class="progress-container" id="progressContainer">
                <div class="progress-bar" id="progressBar"></div>
                <span class="progress-text" id="progressText">0%</span>
            </div>

            <!-- 多文件进度列表 -->
            <div id="fileProgressList"></div>

            <button type="submit" class="upload-button">✅ 上传文件</button>
        </form>
    </div>

    <script>
        // 全局变量
        let allFiles = [];
        let currentPage = 1;
        let pageSize = parseInt(document.getElementById('pageSizeSelect').value);
        let selectedFiles = [];

        // DOM元素
        const fileInput = document.getElementById('fileInput');
        const fileInfo = document.getElementById('fileInfo');
        const uploadForm = document.getElementById('uploadForm');
        const progressContainer = document.getElementById('progressContainer');
        const progressBar = document.getElementById('progressBar');
        const progressText = document.getElementById('progressText');
        const fileProgressList = document.getElementById('fileProgressList');

        // 页面加载时获取文件列表
        window.onload = function () {
            loadFileList();
        };

        pageSizeSelect.addEventListener('change', function () {
            pageSize = parseInt(this.value);
            currentPage = 1; // 重置到第一页
            sortFilesByName();
            renderFileTable();
            renderPagination();
        });

        // 从后端 API 加载文件列表
        async function loadFileList() {
            try {
                const res = await fetch('/api/GetBackupFiles');
                const data = await res.json();
                allFiles = data.files || [];
                sortFilesByName();
                renderFileTable();
                renderPagination();
            } catch (err) {
                console.error('加载文件列表失败:', err);
                allFiles = [];
                renderFileTable();
                renderPagination();
            }
        }

        function sortFilesByName() {
            allFiles.sort((a, b) => {
                const nameA = a.filename.toLowerCase();
                const nameB = b.filename.toLowerCase();
                return nameA.localeCompare(nameB);
            });
        }

        // 分页逻辑
        function getPaginatedFiles() {
            const start = (currentPage - 1) * pageSize;
            const end = start + pageSize;
            return allFiles.slice(start, end);
        }

        // 渲染文件表格
        function renderFileTable() {
            const tbody = document.getElementById('fileTableBody');
            const files = getPaginatedFiles();

            tbody.innerHTML = '';
            if (files.length === 0) {
                tbody.innerHTML = '<tr><td colspan="4" style="text-align: center; color: #999;">暂无文件</td></tr>';
                return;
            }

            files.forEach(file => {
                const tr = document.createElement('tr');
                tr.innerHTML = `
                    <td style="text-align: left; padding: 12px;">
                        <a href="/download/${encodeURIComponent(file.filename)}" target="_blank">📄 ${file.filename}</a>
                    </td>
                    <td style="text-align: right; padding: 12px;">${formatTimestamp(file.time)}</td>
                    <td style="text-align: right; padding: 12px;">${formatFileSize(file.size)}</td>
                    <td style="text-align: left; padding: 12px;">
                        <button onclick="deleteFile('${file.filename}')" style="
                            padding: 4px 8px;
                            background: #e74c3c;
                            color: white;
                            border: none;
                            border-radius: 4px;
                            cursor: pointer;
                            font-size: 12px;
                        ">🗑️ 删除</button>
                    </td>
                `;
                tbody.appendChild(tr);
            });
        }

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';

            const units = ['Bytes', 'KB', 'MB', 'GB'];
            const threshold = 1024;
            let unitIndex = 0;
            let size = bytes;

            while (size >= threshold && unitIndex < units.length - 1) {
                size /= threshold;
                unitIndex++;
            }

            const formattedSize = size % 1 === 0 ?
                size.toFixed(0) :
                size.toFixed(2).replace(/\.?0+$/, '');
            return `${formattedSize} ${units[unitIndex]}`;
        }

        // 格式化时间戳
        function formatTimestamp(timestamp) {
            if (!timestamp) return '未知时间';
            const date = new Date(timestamp * 1000);
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
            }).replace(/\//g, '-');
        }

        // 渲染分页按钮
        function renderPagination() {
            const pagination = document.getElementById('pagination');
            const totalPages = Math.ceil(allFiles.length / pageSize);

            pagination.innerHTML = '';

            const prevBtn = document.createElement('button');
            prevBtn.textContent = '上一页';
            prevBtn.disabled = currentPage === 1;
            prevBtn.onclick = () => {
                if (currentPage > 1) {
                    currentPage--;
                    renderFileTable();
                    renderPagination();
                }
            };
            pagination.appendChild(prevBtn);

            const pageInfo = document.createElement('span');
            pageInfo.className = 'page-info';
            pageInfo.textContent = `第 ${currentPage} 页，共 ${totalPages} 页`;
            pagination.appendChild(pageInfo);

            const nextBtn = document.createElement('button');
            nextBtn.textContent = '下一页';
            nextBtn.disabled = currentPage === totalPages;
            nextBtn.onclick = () => {
                if (currentPage < totalPages) {
                    currentPage++;
                    renderFileTable();
                    renderPagination();
                }
            };
            pagination.appendChild(nextBtn);
        }

        // 文件选择事件
        fileInput.addEventListener('change', function () {
            selectedFiles = Array.from(fileInput.files);
            updateFileInfo();
        });

        // 更新已选文件信息
        function updateFileInfo() {
            if (selectedFiles.length === 0) {
                fileInfo.textContent = '暂未选择文件';
                return;
            }
            let text = '<strong>已选择文件：</strong><br>';
            selectedFiles.forEach(f => {
                text += `📄 ${f.name} (${formatFileSize(f.size)})<br>`;
            });
            fileInfo.innerHTML = text;
        }

        // 上传表单提交（使用XMLHttpRequest实现实时进度）
        uploadForm.addEventListener('submit', function (e) {
            e.preventDefault();

            if (selectedFiles.length === 0) {
                alert('请先选择至少一个文件！');
                return;
            }

            // 显示进度条
            progressContainer.style.display = 'block';
            progressBar.style.width = '0%';
            progressText.textContent = '0%';
            fileProgressList.innerHTML = '';

            // 为每个文件创建进度条
            const fileProgressMap = {};
            selectedFiles.forEach(file => {
                const fileId = encodeURIComponent(file.name);

                // 进度条
                const progressItem = document.createElement('div');
                progressItem.className = 'file-progress-item';
                progressItem.innerHTML = `
                    <div class="file-name">${file.name}</div>
                    <div class="progress-container">
                        <div class="progress-bar" id="file-progress-${fileId}"></div>
                        <span class="progress-text" id="file-progress-text-${fileId}">0%</span>
                    </div>
                `;
                fileProgressList.appendChild(progressItem);

                // 初始化进度状态
                fileProgressMap[fileId] = {
                    file: file,
                    loaded: 0,
                    total: file.size,
                    status: 'pending'
                };
            });

            // 创建上传结果区域
            const resultContainer = document.createElement('div');
            resultContainer.className = 'upload-result';
            resultContainer.innerHTML = `
                <div class="upload-result-title">上传结果：</div>
                <div class="upload-result-list" id="uploadResultList"></div>
            `;
            fileProgressList.appendChild(resultContainer);

            // 使用 FormData 包装文件
            const formData = new FormData();
            selectedFiles.forEach(file => formData.append('file', file));

            // 使用 XMLHttpRequest 实现精确进度监控
            const xhr = new XMLHttpRequest();
            xhr.open('POST', '/upload', true);

            // 监听总上传进度
            xhr.upload.addEventListener('progress', function (e) {
                if (e.lengthComputable) {
                    const totalPercent = Math.round((e.loaded / e.total) * 100);
                    progressBar.style.width = totalPercent + '%';
                    progressText.textContent = totalPercent + '%';

                    // 计算每个文件的进度（模拟）
                    const avgProgress = e.loaded / e.total;
                    Object.keys(fileProgressMap).forEach(fileId => {
                        const progress = fileProgressMap[fileId];
                        progress.loaded = Math.floor(progress.total * avgProgress);
                        updateFileProgress(fileId, progress);
                    });
                }
            });

            // 上传完成处理
            xhr.onload = function () {
                try {
                    const response = JSON.parse(xhr.responseText);
                    displayUploadResult(response);

                    // 上传成功时刷新文件列表
                    if (response.success_count > 0) {
                        setTimeout(loadFileList, 1000);
                    }
                } catch (e) {
                    displayUploadError('解析服务器响应失败');
                }
            };

            xhr.onerror = function () {
                displayUploadError('网络错误，上传失败');
            };

            xhr.send(formData);
        });

        // 更新单个文件进度
        function updateFileProgress(fileId, progress) {
            const percent = Math.round((progress.loaded / progress.total) * 100);
            const fileProgressBar = document.getElementById(`file-progress-${fileId}`);
            const fileProgressText = document.getElementById(`file-progress-text-${fileId}`);
            if (fileProgressBar && fileProgressText) {
                fileProgressBar.style.width = percent + '%';
                fileProgressText.textContent = percent + '%';
            }
        }

        // 显示上传结果
        function displayUploadResult(result) {
            const resultList = document.getElementById('uploadResultList');
            resultList.innerHTML = '';

            // 显示成功文件
            if (result.success_files && result.success_files.length > 0) {
                result.success_files.forEach(file => {
                    const item = document.createElement('div');
                    item.className = 'upload-result-item upload-success';
                    item.innerHTML = `✅ ${file} 上传成功`;
                    resultList.appendChild(item);
                });
            }

            // 显示失败文件
            if (result.fail_files && result.fail_files.length > 0) {
                result.fail_files.forEach(file => {
                    const item = document.createElement('div');
                    item.className = 'upload-result-item upload-failed';
                    item.innerHTML = `❌ ${file} 上传失败`;
                    resultList.appendChild(item);
                });
            }

            // 显示统计信息
            const summary = document.createElement('div');
            summary.className = 'upload-result-item';
            summary.style.fontWeight = 'bold';
            summary.style.marginTop = '10px';
            summary.textContent = `总计: ${result.total_count || 0}个文件, 成功: ${result.success_count || 0}个, 失败: ${result.fail_count || 0}个`;
            resultList.appendChild(summary);
        }

        // 显示上传错误
        function displayUploadError(message) {
            const resultList = document.getElementById('uploadResultList');
            resultList.innerHTML = `
                <div class="upload-result-item upload-failed">❌ ${message}</div>
            `;
        }

        // 删除文件
        async function deleteFile(filename) {
            if (!confirm(`确定要删除文件 "${filename}" 吗？`)) return;

            try {
                const response = await fetch(`/delete/${encodeURIComponent(filename)}`, {
                    method: 'DELETE',
                });

                if (response.ok) {
                    alert(`✅ 文件 "${filename}" 删除成功！`);
                    loadFileList();
                } else {
                    const errorMsg = await response.text();
                    alert(`❌ 删除失败：${errorMsg || '未知错误'}`);
                }
            } catch (err) {
                console.error('删除请求出错:', err);
                alert(`❌ 删除请求失败：${err.message}`);
            }
        }
    </script>
</body>

</html>